package router

import (
	"api-fiber-gorm/api/chat"
	"api-fiber-gorm/api/goods"
	"api-fiber-gorm/api/member"
	"api-fiber-gorm/handler"
	"api-fiber-gorm/middleware"
	"api-fiber-gorm/ws"
	"encoding/json"
	swagger "github.com/arsmn/fiber-swagger/v2"
	_ "github.com/arsmn/fiber-swagger/v2/example/docs"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/websocket/v2"
	"log"
)

// SetupRoutes setup router api
func SetupRoutes(app *fiber.App) {
	// Middleware
	api := app.Group("/api", logger.New())
	api.Get("/", handler.Hello)

	//app.Get("/docs/*", swagger.Handler)
	app.Get("/docs/*", swagger.New())

	// Auth
	auth := api.Group("/auth")
	auth.Post("/login", handler.Login)

	// User
	user := api.Group("/user")
	user.Get("/:id", handler.GetUser)
	user.Post("/", handler.CreateUser)
	user.Patch("/:id", middleware.Protected(), handler.UpdateUser)
	user.Delete("/:id", middleware.Protected(), handler.DeleteUser)

	// Product
	product := api.Group("/product")
	product.Get("/", handler.GetAllProducts)
	product.Get("/:id", handler.GetProduct)
	product.Post("/", middleware.Protected(), handler.CreateProduct)
	product.Delete("/:id", middleware.Protected(), handler.DeleteProduct)
	//address
	mb := api.Group("/member")
	mb.Get("/:userId", member.GetAdd)

	api.Get("/getFriendList", member.GetFriendList)

	api.Get("/test", member.GetAddressPage)
	od := api.Group("/order")
	od.Get("/:userId", goods.GetorderList)

	//chat 相关的

	api.Get("chat/getMessageList", chat.GetMessageListApi)

	//ws
	app.Get("/ws", websocket.New(func(c *websocket.Conn) {
		//id:=c.Query("id")
		// When the function returns, unregister the client and close the connection
		defer func() {
			ws.Unregister <- c
			c.Close()
		}()
		// Register the client
		ws.Register <- c
		//msg:="欢迎您:"+id
		//err:=c.WriteMessage(1, []byte(c.Conn))
		//log.Println(err)
		for {
			var msg = &ws.MessageTemplate{}
			messageType, message, err := c.ReadMessage()
			err = json.Unmarshal(message, msg)
			log.Println(msg)
			log.Println(err)
			if err != nil {
				if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
					log.Println("read error:", err)
				}
				return
			}
			if messageType == websocket.TextMessage {
				//msg.Data=string(message)
				ws.Msg <- *msg
				//ws.Broadcast <- string(message)
			} else {
				log.Println("websocket message received of type", messageType)
			}
		}
	}))
}
